package com.tongji.housediy.view.components
{
	import com.tongji.housediy.utils.CollisionDetection;
	import com.tongji.housediy.utils.DragDropManager;
	import com.tongji.housediy.utils.MathCalculation;
	
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.filters.DropShadowFilter;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	import mx.controls.Alert;
	import mx.core.UIComponent;
	
	/**
	 * 
	 * @author chenchao
	 * 
	 */
	public class RotationBtn extends Sprite
	{
		[Embed(source="assets/images/rotationBtn.png")]
		private var RotateData:Class;
		
		private var tempX:Number;
		private var tempY:Number;
		
		private var _relatedObj:UIComponent;
		
		private var fixedRoomX:Number;
		private var fixedRoomY:Number;
		
		private var rectangle:Rectangle;

		
		private var onceFlag:int;
		private var tmpRotateState:int;
		private var reverseRotation:Number;
		private var segPoint:Point;
		private var oldData:Vector.<Number> = new Vector.<Number>;
		
		//caddy 3.23
		private var lastRectangle:Rectangle;
		private var oldRotation:Number = 0;
		private var firstX:Number;
		private var firstY:Number;
		private var lastRotation:Number;
		
		public function get relatedObj():UIComponent
		{
			return _relatedObj;
		}
		
		public function set relatedObj(value:UIComponent):void
		{
			_relatedObj = value;
		}
		
		/**
		 *旋转时，逐帧旋转 
		 * 
		 */		
		public function RotationBtn()
		{
			var rotationImage:Bitmap = new RotateData();
			rotationImage.filters = [new DropShadowFilter(2)];
			this.addChild(rotationImage);
			
			this.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
			
			this.buttonMode = true;
			
			onceFlag = 0;
		}
		
		private function mouseDownHandler(event:MouseEvent):void
		{		
			tempX = this.x + 11.5;
			tempY = this.y + 11;
			firstX = this.x + 11.5;
			firstY = this.y + 11;
			
			//保存上一次旋转的角度
			oldRotation = relatedObj.rotation;
			rectangle = (relatedObj as ICommonOperater).updateBoundingAndCenterPoint();

			fixedRoomX = relatedObj.getRect(relatedObj.parent).x;
			fixedRoomY = relatedObj.getRect(relatedObj.parent).y;
			
			if (relatedObj is NormalDoor)
			{
				onceFlag = 0;
				segPoint = MathCalculation.getOffsetValue(((relatedObj.parent) as RoomBorder).k, (relatedObj as NormalDoor).length, ((relatedObj.parent) as RoomBorder).data);
				reverseRotation = (relatedObj as NormalDoor).getReverseRotation((relatedObj as AbstractBorderChild).data, ((relatedObj.parent) as RoomBorder).k);
				tmpRotateState = (relatedObj as NormalDoor).rotateState;
				
				if((relatedObj as NormalDoor).rotateState == 1 || (relatedObj as NormalDoor).rotateState == 2 )
				{
					(relatedObj as NormalDoor).segFlag = false;
				}
				else if ((relatedObj as NormalDoor).rotateState == 3 || (relatedObj as NormalDoor).rotateState == 4)
				{
					(relatedObj as NormalDoor).segFlag = true;
				}
				copyData(oldData, (relatedObj as AbstractBorderChild).data);
			}
			
			this.removeEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
			this.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
			this.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
			this.startDrag();
			
			event.stopImmediatePropagation();
		}
		
		private function mouseUpHandler(event:MouseEvent):void
		{
			this.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
			this.removeEventListener(Event.ENTER_FRAME, enterFrameHandler);			

			if (relatedObj is AbstractDrawingRoom || relatedObj is Furniture)
			{		
				rectangle = (relatedObj as ICommonOperater).updateBoundingAndCenterPoint();
			    this.x = rectangle.x + rectangle.width / 2 - 11.5;
			    this.y = rectangle.y + rectangle.height + 20;
			}
				
			else if (relatedObj is NormalDoor)
			{
				copyData((relatedObj as AbstractBorderChild).data, oldData);
				
				(relatedObj as NormalDoor).rotateState = tmpRotateState;
				if((relatedObj as NormalDoor).rotateState == 1 || (relatedObj as NormalDoor).rotateState == 4)
				{
					(relatedObj as AbstractBorderChild).calculateRotateBtn((relatedObj as AbstractBorderChild).data, ((relatedObj.parent) as RoomBorder).k);
					this.x = (relatedObj as AbstractBorderChild).rotationBtnX + relatedObj.parent.parent.x;
					this.y = (relatedObj as AbstractBorderChild).rotationBtnY + relatedObj.parent.parent.y;
				}
				else if((relatedObj as NormalDoor).rotateState == 2 || (relatedObj as NormalDoor).rotateState == 3)
				{
					(relatedObj as AbstractBorderChild).calculateRotateBtn((relatedObj as AbstractBorderChild).data, ((relatedObj.parent) as RoomBorder).k, false);
					this.x = (relatedObj as AbstractBorderChild).rotationBtnX + relatedObj.parent.parent.x;
					this.y = (relatedObj as AbstractBorderChild).rotationBtnY + relatedObj.parent.parent.y;
				}
			}
			this.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
			this.stopDrag();
		}
		
		private function enterFrameHandler(event:Event):void
		{
			var totalRotation:Number;
			var newRotation:Number;
			
			if (relatedObj is Furniture)
			{				
				newRotation = MathCalculation.getRotationAngle(rectangle.x + rectangle.width / 2, rectangle.y + rectangle.height / 2, firstX, firstY, this.x + 11.5, this.y + 11);			
				totalRotation = (newRotation*180/Math.PI + oldRotation)%360;
				
				//在固定角度90，180, 270， 360有停顿的效果
				if(totalRotation > 0 && (Math.abs(totalRotation - 90) <= 10))
				{					
				    if(90 != Math.abs(totalRotation))	
						relatedObj.rotation = 90;			   	
				 }
				else if(totalRotation < 0 && (Math.abs(totalRotation + 90) <= 10))
				{					
					if(-90 != Math.abs(totalRotation))	
						relatedObj.rotation = -90;				   	
				}
				 else if(totalRotation > 0 && (Math.abs(totalRotation - 180) <= 10))
				 {							   
					 if(180 != Math.abs(totalRotation))
						 relatedObj.rotation = 180;				 
				 }
				 else if(totalRotation < 0 && (Math.abs(totalRotation ) <= 10))
				{
					 if(0 != Math.abs(totalRotation))
						 relatedObj.rotation = 0;
				}
				 else
				 {					 
					 relatedObj.rotation = totalRotation;
				 }
				
				//碰撞检测，如发生碰撞，则返回上一帧的状态
				if (CollisionDetection.isCollisionWithOther(relatedObj))
				{				
					relatedObj.rotation = lastRotation;
				}
				else
				{
					tempX = this.x + 11.5;
					tempY = this.y + 11;
					
					lastRotation = relatedObj.rotation;
				}
			}
			else if (relatedObj is NormalDoor)
			{
				rotation = MathCalculation.getRotationAngle(rectangle.x + rectangle.width / 2, rectangle.y + rectangle.height / 2, tempX, tempY, this.x + 11.5, this.y + 11);
				
				if(rotation >= 0 && rotation <= Math.PI * 0.5)
				{
					if(onceFlag != 1)
					{
						this.rotateDoor(0);
						onceFlag = 1;
					}
				}
				else if (rotation > Math.PI * 0.5 && rotation <= Math.PI)
				{
					if(onceFlag != 2)
					{
						this.rotateDoor(1);
						onceFlag = 2;
					}
				}
				else if (rotation > -Math.PI && rotation <= Math.PI * (-0.5))
				{
					if(onceFlag != 3)
					{
						this.rotateDoor(2);
						onceFlag = 3;
					}
				}
				else if (rotation > Math.PI * (-0.5) && rotation < 0)
				{
					if(onceFlag != 4)
					{
						this.rotateDoor(3);
						onceFlag = 4;
					}
				}
			}
		}
		
		private function copyData(vec1:Vector.<Number>, vec2:Vector.<Number>):void
		{
			for(var i:int = 0; i < 4; i++)
			{
				vec1[i] = vec2[i];
			}
		}
		
		private function rotateDoor(time:int):void
		{
			this.doFirstRotate();
			this.rotateDoorTimes(time);
			this.rotateDoorState();
		}
		
		private function doFirstRotate():void
		{
			tmpRotateState = (relatedObj as NormalDoor).rotateState;
			
			if ((relatedObj as NormalDoor).rotateState == 2 || (relatedObj as NormalDoor).rotateState == 4)
			{
				this.rotateDoorTimes(1);
				this.rotateDoorState();
			}
		}
		
		private function rotateDoorState():void
		{
			(relatedObj as AbstractBorderChild).transformNormalDoorState(segPoint, reverseRotation, tmpRotateState, (relatedObj as NormalDoor).segFlag);
			
			if (tmpRotateState == 3 || tmpRotateState == 4)
			{
				if (!(relatedObj as NormalDoor).segFlag)
					(relatedObj as NormalDoor).segFlag = true;
			}
			else
			{
				if ((relatedObj as NormalDoor).segFlag)
					(relatedObj as NormalDoor).segFlag = false;
			}
		}
		
		private function rotateDoorTimes(time:int):void
		{
			for (var i:int = 0; i < time; i++)
				this.addRotateState();
		}
		
		private function addRotateState():void
		{
			tmpRotateState++;
			if (tmpRotateState == 5)
				tmpRotateState = 1;
		}
	}
}